package com.water.auth.security;
//package com.water.expert.extraction.security;
//
//import java.lang.reflect.Field;
//
////import org.springframework.context.annotation.Bean;
////import org.springframework.context.annotation.Configuration;
////import org.springframework.security.config.annotation.web.builders.HttpSecurity;
////import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
////import org.springframework.security.web.SecurityFilterChain;
//
//import java.security.KeyPair;
//import java.security.KeyPairGenerator;
//import java.security.interfaces.RSAPrivateKey;
//import java.security.interfaces.RSAPublicKey;
//import java.util.UUID;
//
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.core.annotation.Order;
//import org.springframework.http.MediaType;
//import org.springframework.security.config.Customizer;
//import org.springframework.security.config.annotation.web.builders.HttpSecurity;
//import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
//import org.springframework.security.core.userdetails.User;
//import org.springframework.security.core.userdetails.UserDetails;
//import org.springframework.security.core.userdetails.UserDetailsService;
//import org.springframework.security.oauth2.core.AuthorizationGrantType;
//import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
//import org.springframework.security.oauth2.core.oidc.OidcScopes;
//import org.springframework.security.oauth2.jwt.JwtDecoder;
//import org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository;
//import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
//import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
//import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
//import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer;
//import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings;
//import org.springframework.security.oauth2.server.authorization.settings.ClientSettings;
//import org.springframework.security.provisioning.InMemoryUserDetailsManager;
//import org.springframework.security.web.SecurityFilterChain;
//import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
//import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher;
//import org.springframework.security.web.util.matcher.RequestMatcher;
//
//import com.nimbusds.jose.jwk.JWKSet;
//import com.nimbusds.jose.jwk.RSAKey;
//import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
//import com.nimbusds.jose.jwk.source.JWKSource;
//import com.nimbusds.jose.proc.SecurityContext;
//
//@Configuration
//@EnableWebSecurity
//public class SecurityConfigEx {
//	@Bean
//	@Order(1)
//	// 用于协议端点的Spring Security 过滤器链:定义 OAuth2 认证服务器的安全规则
//	public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
//		// 创建 OAuth2 授权服务器配置对象，用于配置 OAuth2 授权服务器 
//		// ✅ 它负责管理 authorization_code 认证流程，以及 client_credentials 授权类型
//		OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = OAuth2AuthorizationServerConfigurer.authorizationServer();
//		
//		// 设置安全匹配规则 (securityMatcher)，只处理 OAuth2 相关的请求
//		// ✅确保 HttpSecurity 只处理 OAuth2 相关的 URL 
//		// ✅ getEndpointsMatcher() 自动匹配 /oauth2/token, /oauth2/authorize等 OAuth2 端点
//		// ✅ 其他 URL 仍然可以使用普通的 Spring Security 规则
//		 // 获取 OAuth2 端点匹配器
//	    RequestMatcher endpointsMatcher = authorizationServerConfigurer.getEndpointsMatcher();
//	    http.securityMatcher(endpointsMatcher);
//		
//		// 启用 OpenID Connect（OIDC）
//		// ✅ 启用 OIDC（OpenID Connect），支持 id_token 授权 
//		// ✅ OIDC 用于用户身份验证，允许客户端获取用户信息 
//		// ✅ Customizer.withDefaults() 表示使用默认 OIDC 配置
//		http.with(authorizationServerConfigurer,(authorizationServer) -> authorizationServer.oidc(Customizer.withDefaults()));
//
//		// 允许访问登录页面
//		http.authorizeHttpRequests(auth -> auth.requestMatchers("/login","/custom-login").permitAll());
//		// 保护所有 API 访问
//		// ✅ 所有 HTTP 请求必须经过身份验证
//		// ✅ 确保未认证用户无法访问受保护资源
//		http.authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated());
//				
//		// 配置异常处理（登录入口）
//		// ✅ 定义默认认证入口，未认证用户会被重定向到 /login 页面 
//		// ✅ 如果访问的是 HTML 页面，则使用 LoginUrlAuthenticationEntryPoint 处理异常
//		http.exceptionHandling((exceptions) -> exceptions.defaultAuthenticationEntryPointFor(
//						new LoginUrlAuthenticationEntryPoint("/login"),
//						new MediaTypeRequestMatcher(MediaType.TEXT_HTML)));
//		// 设置自定义登录页及登录成功后跳转到 /dashboard
//		//http.formLogin(form -> form.loginPage("/login").defaultSuccessUrl("/dashboard", true).permitAll());
//		// 注销后返回登录页
//		//http.logout(logout -> logout.logoutSuccessUrl("/login?logout").permitAll());
//		
//		// 构建安全过滤链
//		return http.build();
//	}
//
//	@Bean
//	@Order(2)
//	// 	用于身份验证的Spring Security 过滤器链
//	public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
////		http.authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated());
////		// 启用表单登录
////		// ✅ 启用表单登录（默认登录页面 /login） 
////		// ✅ 如果用户未登录，Spring Security 自动重定向到 /login 
////		// ✅ 用户登录后，会自动跳转到默认的目标页面
////		http.formLogin(Customizer.withDefaults());
////		return http.build();
//		
//		 http.authorizeHttpRequests(auth -> auth
//             .requestMatchers("/custom-login", "/public/**").permitAll() // 允许访问登录页面和公共资源
//             .anyRequest().authenticated()); // 其他所有请求必须认证
//         http.formLogin(form -> form
//             .loginPage("/custom-login") // 设置自定义登录页面
//             .defaultSuccessUrl("/dashboard", true) // 登录成功后跳转
//             .failureUrl("/custom-login?error") // 登录失败后跳转
//             .permitAll());
//         http.logout(logout -> logout
//             .logoutSuccessUrl("/custom-login?logout") // 退出后回到登录页
//             .permitAll());
//		 return http.build();
//	}
//
//	@Bean
//	// UserDetailsService用于检索用户进行身份验证的实例
//	public UserDetailsService userDetailsService() {
//		UserDetails userDetails = User.withDefaultPasswordEncoder().username("user").password("password").roles("USER")
//				.build();
//
//		return new InMemoryUserDetailsManager(userDetails);
//	}
//
//	@Bean
//	// RegisteredClientRepository用于管理客户端的实例
//	public RegisteredClientRepository registeredClientRepository() {
//		RegisteredClient oidcClient = RegisteredClient.withId(UUID.randomUUID().toString()).clientId("oidc-client")
//				.clientSecret("{noop}secret").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
//				.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
//				.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
//				.redirectUri("http://127.0.0.1:8080/login/oauth2/code/oidc-client")
//				.postLogoutRedirectUri("http://127.0.0.1:8080/").scope(OidcScopes.OPENID).scope(OidcScopes.PROFILE)
//				.clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build()).build();
//
//		return new InMemoryRegisteredClientRepository(oidcClient);
//	}
//
//	@Bean
//	// JWKSource用于签署访问令牌的实例
//	public JWKSource<SecurityContext> jwkSource() {
//		KeyPair keyPair = generateRsaKey();
//		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
//		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
//		RSAKey rsaKey = new RSAKey.Builder(publicKey).privateKey(privateKey).keyID(UUID.randomUUID().toString())
//				.build();
//		JWKSet jwkSet = new JWKSet(rsaKey);
//		return new ImmutableJWKSet<>(jwkSet);
//	}
//
//	// KeyPair用于创建在启动时生成的密钥的实例JWKSource
//	private static KeyPair generateRsaKey() {
//		KeyPair keyPair;
//		try {
//			KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
//			keyPairGenerator.initialize(2048);
//			keyPair = keyPairGenerator.generateKeyPair();
//		} catch (Exception ex) {
//			throw new IllegalStateException(ex);
//		}
//		return keyPair;
//	}
//
//	@Bean
//	// JwtDecoder用于解码签名访问令牌的实例
//	public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
//		return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource);
//	}
//
//	@Bean
//	public AuthorizationServerSettings authorizationServerSettings() {
//		return AuthorizationServerSettings.builder().build();
//	}
//
//}